package com.project.poetry.service.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.project.poetry.common.constant.DictConstant;
import com.project.poetry.common.util.CommonUtil;
import com.project.poetry.service.entity.dto.notes.AllusionInDTO;
import com.project.poetry.service.entity.dto.notes.AllusionOutDTO;
import com.project.poetry.service.entity.dto.notes.AllusionPoetryDTO;
import com.project.poetry.service.entity.dto.notes.NotesDTO;
import com.project.poetry.service.entity.po.notes.NotesPO;
import com.project.poetry.service.mapper.NotesMapper;
import com.project.poetry.service.service.NotesService;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 注释业务层实现类
 * @author mengxj
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class NotesServiceImpl extends ServiceImpl<NotesMapper, NotesPO> implements NotesService {

    @Resource
    private NotesMapper notesMapper;

    @Override
    public void saveNotes(NotesDTO notes) {
        Long id = notes.getId();
        NotesPO po = new NotesPO();
        BeanUtils.copyProperties(notes, po);
        if(Objects.isNull(id)){
            super.save(po);
        }else{
            super.updateById(po);
        }
    }

    @Override
    public List<NotesDTO> notesList(Long poetryId) {
        LambdaQueryWrapper<NotesPO> wrapper = new QueryWrapper<NotesPO>().lambda();
        if(Objects.nonNull(poetryId)){
            wrapper.eq(NotesPO :: getPoetryId, poetryId);
        }
        List<NotesPO> list = this.notesMapper.selectList(wrapper);
        return CommonUtil.isEmpty(list) ? new ArrayList<>() : list.stream().map(po -> {
            NotesDTO dto = new NotesDTO();
            BeanUtils.copyProperties(po, dto);
            return dto;
        }).collect(Collectors.toList());
    }

    @Override
    public IPage<AllusionOutDTO> allusionList(AllusionInDTO allusion) {
        Integer pageNum = allusion.getPageNum(), pageSize = allusion.getPageSize();
        QueryWrapper<AllusionOutDTO> wrapper = new QueryWrapper<>();
        CommonUtil.eq(wrapper, "tn.is_allusion", DictConstant.TRUE);
        CommonUtil.eq(wrapper, "tn.poetry_id", allusion.getPoetryId());
        CommonUtil.like(wrapper, "tn.key_word", allusion.getKeyWord());
        wrapper.orderByAsc("tn.poetry_id");
        return this.notesMapper.allusionList(CommonUtil.getPage(pageNum, pageSize), wrapper);
    }

    @Override
    public List<AllusionPoetryDTO> allusionPoetry() {
        return this.notesMapper.allusionPoetry();
    }
}
